//
//  ITSuperPlayerViewController.m
//  InduceTool
//
//  Created by 魏延龙 on 2020/9/3.
//  Copyright © 2020 魏延龙. All rights reserved.
//

#import "ITSuperPlayerViewController.h"
#import <SuperPlayer/SuperPlayer.h>
#import <Masonry.h>
#import "CFDanmakuView.h"

@interface ITSuperPlayerViewController ()<SuperPlayerDelegate, CFDanmakuDelegate>

@property (nonatomic, strong) UIView *holdView;
@property (nonatomic, strong) SuperPlayerView *playerView;
@property CFDanmakuView *danmakuView;
@end

@implementation ITSuperPlayerViewController

- (void)dealloc
{
    NSLog(@"ITSuperPlayerViewController dealloc");
}

- (instancetype)init {
    if (SuperPlayerWindowShared.backController) {
        [SuperPlayerWindowShared hide];
        ITSuperPlayerViewController *playerViewCtrl = (ITSuperPlayerViewController *)SuperPlayerWindowShared.backController;
        return playerViewCtrl;
    } else {
        if (self = [super init]) {
        }
        return self;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initHoldView];
    
    [self initPlayerView];
    [self setupDanmakuData];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    SuperPlayerWindowShared.superPlayer = _playerView; // 设置小窗显示的播放器
    SuperPlayerWindowShared.backController = self;  // 设置返回的view controller
    [SuperPlayerWindowShared show]; // 悬浮显示
}

// 返回值要必须为NO
//- (BOOL)shouldAutorotate {
//    return YES;
//}
//
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleDarkContent;
//}
//
//- (BOOL)prefersStatusBarHidden {
//    return self.playerView.isFullScreen;
//}

-(void)initHoldView {
    self.holdView = [[UIView alloc] init];
    self.holdView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.holdView];
    [self.holdView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.mas_equalTo(20+self.navigationController.navigationBar.bounds.size.height);
        }
        make.leading.trailing.mas_equalTo(0);
        // 这里宽高比16：9,可自定义宽高比
        make.height.mas_equalTo(self.holdView.mas_width).multipliedBy(9.0f/16.0f);
    }];
    
}
-(void)initPlayerView {
    _playerView = [[SuperPlayerView alloc] init];
    // 设置代理，用于接受事件
    _playerView.delegate = self;
    // 设置父View，_playerView会被自动添加到holderView下面
    _playerView.fatherView = self.holdView;
    
    // 代理里面没有判断外界是否实现
//    _playerView.controlView.delegate = self;
    
    // 支持自定义controlView
//    SPWeiboControlView *weiboControlView = [[SPWeiboControlView alloc] init];
//    _playerView.controlView = weiboControlView;
    
    SuperPlayerModel *playerModel = [[SuperPlayerModel alloc] init];
    // 设置播放地址，直播、点播都可以
    playerModel.videoURL = @"http://200024424.vod.myqcloud.com/200024424_709ae516bdf811e6ad39991f76a4df69.f20.mp4";
    
    
//    SuperPlayerUrl *url1 = [SuperPlayerUrl new];
//    url1.url = @"http://200024424.vod.myqcloud.com/200024424_709ae516bdf811e6ad39991f76a4df69.f20.mp4";
//    url1.title = @"超清";
//    SuperPlayerUrl *url2 = [SuperPlayerUrl new];
//    url2.url = @"http://200024424.vod.myqcloud.com/200024424_709ae516bdf811e6ad39991f76a4df69.f20.mp4";
//    url2.title = @"高清";
//    SuperPlayerUrl *url3 = [SuperPlayerUrl new];
//    url3.url = @"http://200024424.vod.myqcloud.com/200024424_709ae516bdf811e6ad39991f76a4df69.f20.mp4";
//    url3.title = @"标清";
//    SuperPlayerModel *playerModel = [[SuperPlayerModel alloc] init];
//    playerModel.multiVideoURLs = @[url1, url2, url3];
//    playerModel.videoURL = url1.url; // 设置默认播放的清晰度
    
    // 开始播放
    [_playerView playWithModel:playerModel];
}

#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
#define font [UIFont systemFontOfSize:15]
- (void)setupDanmakuData
{
    NSString *danmakufile = [[NSBundle mainBundle] pathForResource:@"danmakufile" ofType:nil];
    NSArray *danmakusDicts = [NSArray arrayWithContentsOfFile:danmakufile];
    
    NSMutableArray* danmakus = [NSMutableArray array];
    for (NSDictionary* dict in danmakusDicts) {
        CFDanmaku* danmaku = [[CFDanmaku alloc] init];
        NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:dict[@"m"] attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : kRandomColor}];
        
        NSString* emotionName = [NSString stringWithFormat:@"smile_%u", arc4random_uniform(90)];
        UIImage* emotion = [UIImage imageNamed:emotionName];
        if (nil != emotion) {
            NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
            attachment.image = emotion;
            attachment.bounds = CGRectMake(0, -font.lineHeight*0.3, font.lineHeight*1.5, font.lineHeight*1.5);
            NSAttributedString *emotionAttr = [NSAttributedString attributedStringWithAttachment:attachment];
            [contentStr appendAttributedString:emotionAttr];
        }
        
        danmaku.contentStr = contentStr;
        
        NSString* attributesStr = dict[@"p"];
        NSArray* attarsArray = [attributesStr componentsSeparatedByString:@","];
        danmaku.timePoint = [[attarsArray firstObject] doubleValue] / 1000;
        danmaku.position = [attarsArray[1] integerValue];
        [danmakus addObject:danmaku];
    }
    
    _danmakuView = [[CFDanmakuView alloc] initWithFrame:CGRectZero];
    _danmakuView.duration = 6.5;
    _danmakuView.centerDuration = 2.5;
    _danmakuView.lineHeight = 25;
    _danmakuView.maxShowLineCount = 15;
    _danmakuView.maxCenterLineCount = 5;
    [_danmakuView prepareDanmakus:danmakus];
    
    _danmakuView.delegate = self;
    [self.playerView addSubview:_danmakuView];
    
    [_danmakuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playerView);
        make.bottom.equalTo(self.playerView);
        make.left.equalTo(self.playerView);
        make.right.equalTo(self.playerView);
    }];
    
    SPDefaultControlView *dv = (SPDefaultControlView *)self.playerView.controlView;
    [dv.danmakuBtn addTarget:self action:@selector(danmakuShow:) forControlEvents:UIControlEventTouchUpInside];
}

static NSTimeInterval danmaku_start_time; // 测试用的，因为demo里的直播时间可能非常大，本地的测试弹幕时间很短

- (NSTimeInterval)danmakuViewGetPlayTime:(CFDanmakuView *)danmakuView
{
    if (_playerView.isLive) {
        return self.playerView.playCurrentTime - danmaku_start_time;
    }
    return self.playerView.playCurrentTime;
}

- (BOOL)danmakuViewIsBuffering:(CFDanmakuView *)danmakuView
{
    return self.playerView.state != StatePlaying;
}

- (void)danmakuShow:(UIButton *)btn {
    if (btn.selected) {
        [_danmakuView start];
        _danmakuView.hidden = NO;
        danmaku_start_time = self.playerView.playCurrentTime;
    } else {
        [_danmakuView pause];
        _danmakuView.hidden = YES;
    }
}

#pragma mark - SuperPlayerDelegate
/// 返回事件
- (void)superPlayerBackAction:(SuperPlayerView *)player {
    
}
/// 全屏改变通知
- (void)superPlayerFullScreenChanged:(SuperPlayerView *)player {
    [[UIApplication sharedApplication] setStatusBarHidden:player.isFullScreen];
}
/// 播放开始通知
- (void)superPlayerDidStart:(SuperPlayerView *)player {
    
}
/// 播放结束通知
- (void)superPlayerDidEnd:(SuperPlayerView *)player {
    
}
/// 播放错误通知
- (void)superPlayerError:(SuperPlayerView *)player errCode:(int)code errMessage:(NSString *)why {
    
}

@end
